package com.itheima.controller;


import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Diet;
import com.itheima.service.DietService;
import com.itheima.utils.POIUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/diet")
public class DietController {

    @Reference
    private DietService dietService;
    @RequestMapping("/upload")
    public Result upload(@RequestParam("excelFile")MultipartFile excelFile){
        try {
            List<String[]> list = POIUtils.readExcel(excelFile);
            if(list!=null&&list.size()>0){
                for (String[] strings : list) {
                    Diet diet = new Diet(strings[0], strings[1], strings[2], strings[3]);
                    dietService.add(diet);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.IMPORT_DIET_FAIL);
        }
        return new Result(true,MessageConstant.IMPORT_DIET_SUCCESS);
    }
    @PreAuthorize("hasAuthority('DIET_QUERY')")
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        return dietService.queryPage(queryPageBean);
    }
    @PreAuthorize("hasAuthority('DIET_ADD')")
    @RequestMapping("/add")
    public Result add(@RequestBody Diet diet){
        try {
            dietService.add(diet);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_DIET_FALL);
        }
        return new Result(true,MessageConstant.ADD_DIET_SUCCESS);
    }

}
